<?php
class Category_mo extends CI_Model {

	var $title   = '';
	var $content = '';
	var $date    = '';

	function __construct()
	{
		// Call the Model constructor
		parent::__construct();
	}

	function get_all_category($category_code, $display_order)
	{
		if (is_null($category_code))
		{
			$category_code = '0';
		}

		if (is_null($display_order))
		{
			$display_order = 1;
		}

		$sql = 'SELECT ';
		$sql .=     'category_code, ';
		$sql .=     'category_name_pc, ';
		$sql .=     'category_name_mobile, ';
		$sql .=     'parent_category_code, ';
		$sql .=     'path, ';
		$sql .=     'depth, ';
		$sql .=     'display_order, ';
		$sql .=     'commodity_count_pc, ';
		$sql .=     'commodity_count_mobile, ';
		$sql .=     'last_related_count_datetime, ';
		$sql .=     'public_commodity_count_pc, ';
		$sql .=     'public_commodity_count_mobile, ';
		$sql .=     'last_public_count_datetime ';
		$sql .= 'FROM ';
		$sql .=     'category ';
		$sql .= 'WHERE ';
		$sql .=     'path like CONCAT(\'%\', lpad(' . $display_order . ', 4, 0), \':\', ' . $category_code . ', \'%\')';
		$sql .= 'ORDER BY ';
		$sql .=     'path ';

		return $this->db->query($sql)->result();
	}


	function get_sub_category_list($parent_category_code)
	{
		if ($parent_category_code == NULL)
		{
			return NULL;
		}

		$sql = 'SELECT ';
		$sql .=     'category_code, ';
		$sql .=     'parent_category_code, ';
		$sql .=     'category_name_pc, ';
		$sql .=     'display_order ';
		$sql .= 'FROM ';
		$sql .=     'category ';
		$sql .= 'WHERE ';
		$sql .=     'parent_category_code = \'' . $parent_category_code . '\' ';
		$sql .= 'ORDER BY ';
		$sql .=     'display_order';

		return $this->db->query($sql)->result();
	}


	function update_display_order($update_data)
	{
		$result = 9;

// 		try {
			if (is_null($update_data))
			{
				return NULL;
			}

			$sp = 'CALL change_category_priority(?, @result)';
			$sql = 'SELECT @result AS result';

			$this->db->query($sp, array('param'=>$update_data));
			$query = $this->db->query($sql);

			foreach ($query->result_array() as $row)
			{
				$result = $row['result'];
			}
// 		} catch (Exception $e) {
// 			log_message('error', $e->getMessage());
// 			$result = 9;
// 		}

		return $result;
	}


	function get_last_ten_entries()
	{
		$query = $this->db->get('entries', 10);
		return $query->result();
	}

	function insert_entry()
	{
		$this->title   = $_POST['title']; // please read the below note
		$this->content = $_POST['content'];
		$this->date    = time();

		$this->db->insert('entries', $this);
	}

	function update_entry()
	{
		$this->title   = $_POST['title'];
		$this->content = $_POST['content'];
		$this->date    = time();

		$this->db->update('entries', $this, array('id' => $_POST['id']));
	}

}